import ctypes
import time
import pyautogui
from win32con import WM_INPUTLANGCHANGEREQUEST
import win32gui
import win32api

def smart_type(text):
    """智能输入（自动处理中英文输入法）"""
    # 确保英文输入状态
    # pyautogui.hotkey('ctrl', 'space')  # 切换英文输入法
    time.sleep(0.3)

    # 分段处理连续大小写
    from itertools import groupby
    groups = groupby(text, key=lambda c: c.isupper())

    for is_upper, chars in groups:
        s = ''.join(chars)
        if is_upper:
            with pyautogui.hold('shift'):
                pyautogui.write(s.lower(), interval=0.05)
        else:
            pyautogui.write(s, interval=0.05)


def switch_to_english():
    # 美式键盘的 HKL (Input Locale ID) 是 0x04090409
    ENG_HKL = 0x04090409  # 英文（美国）键盘
    # 获取前台窗口
    hwnd = ctypes.windll.user32.GetForegroundWindow()
    # 获取线程ID
    thread_id = ctypes.windll.user32.GetWindowThreadProcessId(hwnd, None)
    # 加载英文输入法
    ctypes.windll.user32.LoadKeyboardLayoutW("00000409", 1)  # 加载英文键盘
    # 强制切换输入法
    ctypes.windll.user32.PostMessageW(hwnd, 0x50, 1, ENG_HKL)